/*
 * @Author: Wilbur
 * @Date: 2019-01-08 14:59:16
 * @Last Modified by: Wilbur
 * @Last Modified time: 2019-03-29 16:50:26
 */
<template>
    <div class="container bid-create-wrap">
        <el-form
            v-if="init"
            ref="mainform"
            :model="formData"
            label-position="right"
            status-icon
            :rules="formRule"
            label-width="110px"
            :disabled="false">
            <!-- 赞助商设置 -->
            <div class="form-unit">
                <div class="form-title">赞助商设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="hire_name"
                    label="赞助商:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.hire_name"
                        size="small"
                        class="task-input"/>
                    <span style="display:inline-block;color:#999;margin-left:12px">*赞助商名称字数不超过15字</span>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="hire_logo"
                    label="赞助商Logo:">
                    <el-upload
                        class="avatar-uploader-customer"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false"
                        :http-request="e=> {fnUploadImageOfCustomerLogo(e)}"
                        accept="image/*">
                        <img
                            v-if="formData.hire_logo"
                            :src="formData.hire_logo"
                            class="avatar">
                        <i
                            v-else
                            class="el-icon-plus avatar-uploader-icon"/>
                    </el-upload>
                    <span style="display:inline-block;color:#999;margin-left:12px">*只能上传jpg/png文件</span>
                </el-form-item>
            </div>

            <div class="form-unit">
                <div class="form-title">赞助设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="title"
                    label="赞助标题:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.title"
                        size="small"
                        class="task-input"/>
                    <span style="display:inline-block;color:#999;margin-left:12px">*标题字数不超过20字</span>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="bidTime"
                    label="竞标时间:">
                    <el-date-picker
                        v-model="formData.bidTime"
                        type="datetimerange"
                        range-separator="至"
                        size="small"
                        class="task-input"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间" />
                </el-form-item>

                <el-form-item
                    label="赞助金额(元/人)"
                    required>
                    <el-col class="money-wrap">
                        <el-form-item prop="award_money_min">
                            <el-input
                                placeholder="赞助金额最小值（元）"
                                v-model="formData.award_money_min"
                                size="small"
                                type="number"
                                class="money-input"/>
                        </el-form-item>
                    </el-col>
                    <el-col
                        class="money-line">-</el-col>
                    <el-col class="money-wrap">
                        <el-form-item prop="award_money_max">
                            <el-input
                                placeholder="赞助金额最大值（元）"
                                v-model="formData.award_money_max"
                                size="small"
                                type="number"
                                class="money-input"/>
                        </el-form-item>
                    </el-col>
                </el-form-item>

                <el-form-item
                    label="地区限制">
                    <div>
                        <el-radio
                            size="small"
                            v-model="formData.area_limit"
                            @change="fnAreaLimitChange"
                            :label="0">全国</el-radio>
                        <el-radio
                            size="small"
                            @change="fnAreaLimitChange"
                            v-model="formData.area_limit"
                            :label="1">其他省份限制</el-radio>
                    </div>
                    <div
                        v-show="formData.area_limit == 1"
                        class="provence-list">
                        <el-checkbox-group
                            v-model="formData.limit_pids">
                            <el-checkbox
                                v-for="item in provence"
                                :label="item.id"
                                :key="item.id">{{ item.name }}</el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-form-item>
                <el-form-item
                    label="限定资源"
                    prop="limit_resource_type_nos">
                    <el-checkbox-group v-model="formData.limit_resource_type_nos">
                        <el-checkbox
                            v-for="item in resouceList"
                            :label="item.type_no"
                            :key="item.type_no"
                            name="type">
                            {{ item.type_name }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="intro"
                    label="赞助介绍:">
                    <ueditor
                        v-if="init"
                        ref="ueditor"
                        :default-value="formData.intro"/>

                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="submit_config"
                    label="反馈设置:">
                    <el-checkbox
                        size="small"
                        :true-label="1"
                        :false-label="0"
                        v-model="formData.submit_need_data">提交文本</el-checkbox>
                    <el-checkbox
                        size="small"
                        :true-label="1"
                        :false-label="0"
                        v-model="formData.submit_need_picture">提交图片</el-checkbox>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="contact_wechat"
                    label="微信号:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.contact_wechat"
                        size="small"
                        class="task-input"/>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="contact_hide_before"
                    label="微信号展示:">
                    <el-radio
                        size="small"
                        v-model="formData.contact_hide_before"
                        :label="1">竞标成功后展示</el-radio>
                    <el-radio
                        size="small"
                        v-model="formData.contact_hide_before"
                        :label="0">直接展示</el-radio>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="submit_config"
                    label="竞标填写:">
                    <el-checkbox
                        size="small"
                        :true-label="1"
                        :false-label="0"
                        v-model="formData.accept_need_price">填写报价</el-checkbox>
                    <el-checkbox
                        size="small"
                        :true-label="1"
                        :false-label="0"
                        v-model="formData.accept_need_intro">填写竞标说明
                    <span style="display:inline-block;color:#999;margin-left:12px">*是否需要竞标者填写报价或者竞标说明</span></el-checkbox>
                </el-form-item>
            </div>

            <div class="form-unit">
                <div class="operate-baar">
                    <el-button
                        size="medium"
                        :disabled="bidNo ? true : false"
                        @click="fnReset()">重置</el-button>
                    <el-button
                        size="medium"
                        type="primary"
                        @click="fnSubmit()">提交</el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
import ueditor from '@/components/common/ueditor.vue';
import regin from '@/assets/js/regin.min.js';
export default {
    components: { ueditor },
    data() {
        var validateAwardMoney = (rule, val, callback) => {

            if(!this.formData.award_money_max){
                callback(new Error('请填写最大赞助金额'));
                return;
            }
            if (Number(this.formData.award_money_min) > Number(this.formData.award_money_max)) {
                callback(new Error('赞助金额填写错误'));
                return ;
            }
            callback();
        };

        // 验证二位数组,且数组内元素不为空
        var validateArray = (rule, value, callback) => {
            if (!value) {
                callback(new Error(rule.message));
            } else {
                if (value.length < 2 || !value[0] || !value[1]) {
                    callback(new Error(rule.message));
                    return ;
                }
                callback();
            }
        };

        return {
            authResult: {},
            breadcrumbList: [
                {
                    title: "广告系统",
                },
                {
                    title: "竞标列表",
                    name: 'bidList',
                },
                {
                    title: '添加竞标'
                }
            ],
            bidNo: '',
            provence: [],
            formData: {
                hire_name: '掌上大学赞助平台',
                hire_logo: 'https://cdn.zsdx.cn/wei/images/supply/logo.png',
                title: "",
                bidTime: [this.fnInitTimeNow(), ''],

                intro: "",
                award_money_min: '',
                award_money_max: '',
                area_limit: 0,
                limit_pids: [],
                limit_resource_type_nos: [],
                submit_need_data: 1,
                submit_need_picture: 1,
                contact_wechat: '',
                contact_hide_before: 0,
                accept_need_price: 1,
                accept_need_intro: 1
            },
            formRule: {
                hire_name: [
                    { required: true, message: '请输入赞助商名称', trigger: 'blur' },
                    { min: 1, max: 15, message: '长度在 1 到 15 个字', trigger: 'blur' }
                ],
                hire_logo: [
                    { required: true, message: '请输入赞助商Logo', trigger: 'change' }
                ],
                image_url: [
                    { required: true, message: '请输入任务展示图', trigger: 'change' }
                ],
                title: [
                    { required: true, message: '请输入赞助标题', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字', trigger: 'blur' }
                ],
                award_money_min: [
                    { required: true, message: '请输入最小赞助金额', trigger: 'blur' },
                ],
                contact_wechat: [
                    { required: true, message: '请输入联系人微信', trigger: 'blur' },
                ],
                award_money_max: [
                    { validator: validateAwardMoney, trigger: 'blur' }
                ],
                limit_resource_type_nos: [
                    { type: 'array', required: true, message: '请至少选择限制资源', trigger: 'change' }
                ],
                bidTime: [
                    { required: true, message: '请填写竞标时间', trigger: 'blur' },
                    { validator: validateArray, message: '请填写正确的竞标时间', trigger: 'blur' }
                ],
                intro: [
                    { required: true, message: '请填写赞助介绍', trigger: 'blur' }
                ],
            },
            submitting: false,
            init: false,

            baseUrl: '',
            sessionTicket: localStorage.getItem('sessionTicket'),
            escape: escape,
            resouceList: []
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.$store.commit('SET_HEADER', this.breadcrumbList);

        this.bidNo = this.$route.query.bid_no ? this.$route.query.bid_no : '';

        if (!this.bidNo) {
            this.init = true;
        }else{
            this.fnEditBidInfo();
        }
        this.fnInitProvence();
        this.fnGetResourceSimpleList();
    },
    methods: {
        fnInitTimeNow() {
            var timestamp=new Date().getTime();

            return timestamp;
        },
        fnEditBidInfo() {
            this.$post('/wei4/bid%5Cget', {
                bid_no: this.bidNo
            }, resp => {
                if(resp.code == 1){
                    this.formData = {
                        ...resp.data,
                        bidTime: [new Date(resp.data.start_time * 1000), new Date(resp.data.end_time * 1000)]
                    };
                    this.init = true;
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },
        fnGetResourceSimpleList() {
            this.$post('/wei4/resource_type%5Cget_simple_list', {}, resp => {
                if(resp.code == 1){
                    this.resouceList = resp.data.list;
                }else{
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },
        fnAreaLimitChange() {
            this.formData.limit_pids = [];
        },
        fnInitProvence() {
            let provence = [];

            for(let i = 0; i < regin.length; i++) {
                if(regin[i].id != 0) {
                    provence.push({
                        id: regin[i].id,
                        name: regin[i].name
                    });
                }
            }
            this.provence = provence;
        },
        fnSubmit(){
            if(this.submitting){
                return ;
            }
            this.formData.intro = this.$refs.ueditor ? this.$refs.ueditor.getUEContent() : '';
            this.$refs.mainform.validate(valid => {
                if(valid){
                    this.submitting = true;

                    let data = {
                        hire_name: this.formData.hire_name,
                        hire_logo: this.formData.hire_logo,
                        title: this.formData.title,
                        category: this.formData.category,
                        all_count : this.formData.all_count,
                        start_time: Date.parse(this.formData.bidTime[0])/1000,
                        end_time : Date.parse(this.formData.bidTime[1])/1000,
                        intro: this.formData.intro,
                        award_money_min: this.formData.award_money_min,
                        award_money_max: this.formData.award_money_max,
                        area_limit: this.formData.area_limit,
                        limit_pids: JSON.stringify(this.formData.limit_pids),
                        limit_resource_type_nos: JSON.stringify(this.formData.limit_resource_type_nos),
                        submit_need_data: this.formData.submit_need_data,
                        submit_need_picture: this.formData.submit_need_picture,
                        contact_wechat: this.formData.contact_wechat,
                        contact_hide_before: this.formData.contact_hide_before,
                        accept_need_price: this.formData.accept_need_price,
                        accept_need_intro: this.formData.accept_need_intro
                    };

                    if(this.bidNo){
                        data.bid_no = this.bidNo;

                        this.$post('/wei4/bid%5Cedit', data, resp => {
                            if(resp.code == 1){
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '修改成功'
                                });
                                // this.$refs.mainform.resetFields();
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }else{
                        this.$post('/wei4/bid%5Cadd', data, resp => {
                            if(resp.code == 1){
                                this.bidNo = resp.data.task_no;
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '操作成功'
                                });
                                this.$router.push({
                                    name: 'bidList'
                                });
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }

                }
            });
        },
        /** 数组中删除某个元素 */
        fndeleteItem(list, index, bind) {
            list.splice(index, 1);
            this[bind] = list.length;
        },
        /** 上传组件回调 文件队列修改 */
        fnUploadChange(file, item) {
            item.preview_url = file.url;
        },
        fnBeforeUpload(file, item){
            item.status = 'uploading';
        },
        /** 上传组件回调 上传成功 */
        fnUploadSuccess(resp, file, item) {
            item.img_url = resp.url;
            item.status = 'success';
        },
        fnUploadError(item){
            item.preview_url = '';
            item.status = 'fail';
        },
        fnUpload(e, item) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            item.uploadTime = timeTmp;
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                progress: e.onProgress,
                success: resp => {
                    if(item.uploadTime != timeTmp){
                        return ;
                    }
                    if (resp.code == 1) {
                        // 调用组件成功回调,修改样式
                        e.onSuccess(resp.data, {
                            url: resp.data.url
                        }, this.fileList);
                    } else {
                        // 失败后调用组件error回调,删除对应元素
                        e.onError(resp.msg);
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                    }
                }
            });
        },
        fnUploadImage(e, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                success: resp => {
                    if (resp.code == 1) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },
        fnUploadImageOfCustomerLogo(e) {
            this.fnUploadImage(e, (resp) => {
                this.formData.hire_logo = resp.data.url;
            }, (resp) => {
                console.log(resp.msg);
            });
        },
        fnReset(){
            this.$refs.mainform.resetFields();
        }
    },
};
</script>

<style lang="less" scoped>
    .margin-top{
        margin-top: 15px;
    }
    .bid-create-wrap {
      background: #fff;
      margin: 15px;
      margin-bottom: 0;
      padding: 30px;
      overflow: auto;
    }
    .form-unit {
      margin-bottom: 40px;
    }
    .form-title {
      font-size: 16px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
      line-height: 18px;
      padding: 0 10px;
      border-left: 2px solid #1890ff;
      margin-bottom: 20px;
    }
    .task-input {
      width: 435px !important;
    }
    .money-line{
        width: 35px;
        text-align: center;
    }
    .money-wrap{
        display: inline-block;
        width: 200px;
    }
    .money-input{
        width: 200px!important;
    }
    .task-intro-input {
      width: 750px;
    }
    .table-inner-input {
      outline: none;
      line-height: 20px;
      font-size: 14px;
      width: 100%;
      background: transparent;
      text-align: center;
      cursor: pointer;
    }
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }
    input[type="number"] {
      -moz-appearance: textfield;
    }
    .input-width-delete {
      margin-top: 15px;
      font-size: 0;
      .task-input{
          margin-right: 10px;
      }
    }

    .operate-baar {
      width: 100%;
      text-align: center;
      margin-top: 168px;
    }
    .preview-image {
      width: 120px;
      height: 120px;
      background-position: center;
      background-size: contain;
      background-repeat: no-repeat;
    }

    .pic-width-delete {
      margin-top: 15px;
      float: left;
      margin-right:60px;
      display: inline-block;
      width: 500px;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      .pic-unit {
        flex: 1;
        margin-right: 10px;
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        padding: 15px;
        border-radius: 4px;
        border: 1px solid rgba(217, 217, 217, 1);
        &-index {
          width: 28px;
          height: 28px;
          background: rgba(243, 250, 255, 1);
          border: 1px solid rgba(24, 144, 255, 1);
          margin-right: 15px;
          border-radius: 28px;
          text-align: center;
          line-height: 28px;
          color: rgba(24, 144, 255, 1);
        }
        &-detail{
            flex: 1;
        }
        &-desc{
            width:100%;
        }
        &-textarea{
            resize: none;
            width: 100%;
            height: 44px;
            line-height: 20px;
            border: 0;
            outline: 0;
        }
        .pic-value {
          width:100%;
          height: 215px;
          background-position: center;
          background-size: contain;
          background-repeat: no-repeat;
          background-color: #F6F6F6;
          position: relative;
          .loading{
              width:100%;
              height: 100%;
              line-height: 215px;
              background: rgba(0,0,0,.3);
              transition: opacity .3s ease-in-out;
          }
          .tip{
              font-size: 14px;
              color: #fff;
              line-height: 215px;
              width: 100%;
              height:100%;
              background: rgba(0,0,0,.5);
              position: absolute;
              left: 0;
              top: 0;
              opacity: 0;
              transition: opacity .3s ease-in-out;
          }
          &:hover{
              .loading{
                  opacity: 0;
              }
              .tip{
                  opacity: 1;
              }
          }
        }
        .pic-empty-container{
            display: flex;
            width: 100%;
            height: 100%;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        .pic-empty-plus{
            font-size:24px;
            width: 24px;
            line-height: 24px !important;
            color: rgba(0,0,0,.45);
        }
        .pic-empty-desc{
            font-size:14px;
            color:rgba(0,0,0,0.65);
            line-height:22px;
        }
      }
    }
    .upload-list{
        margin-top:10px;
    }
    .editor-wrap{
        position: relative;
    }
    .uploaded-image{
        width: 360px;
        height: 180px;
        background-size: 100%;
        background-position: center center;
        background-repeat: no-repeat;
        &:hover{
            .icon-delete{
                display: inline-block;
            }
        }
        .icon-delete{
            margin-top: 90px;
            transform: translateY(-50%);
            display: none;
        }
    }
</style>
<style lang="less">
    .avatar-uploader-customer{
        display: inline-block;
        .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 100px;
            height: 100px;
            line-height: 100px;
            text-align: center;
        }
        .avatar {
            width: 100px;
            height: 100px;
            display: block;
        }
    }
    .provence-list{
        .el-checkbox {
            margin-left: 0;
            margin-right: 30px;
        }
    }
</style>
